/*
 * Copyright 北京航空航天大学  @ 2015 版权所有
 */
package com.buaa.edu.leetcode.algorithm.array;

import java.util.Arrays;

import org.junit.Test;

/**
 * <p>
 * 数组旋转
 * For example, 
 * with n = 7 and k = 3, 
 * the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
 * </p>
 * @author towan
 * @email tongwenzide@163.com
 * @time 2015年6月21日
 */
public class RotateArray {

    public void rotate(int[] nums, int k) {
        if(nums==null ||k%nums.length ==0){
            return;
        }
        k = k%nums.length;
        //三次反转
        reverse(nums,0,nums.length-1);
        reverse(nums, 0,k-1);
        reverse(nums,k,nums.length-1);
        
    }
    /**
     * 数组反转
     * @param nums
     * @param start
     * @param end
     * @author towan
     * 2015年6月21日
     */
    private void reverse(int[] nums, int start, int end) {
        while(start<end){
            //交换nums[start]和nums[end]两个数
            int temp = nums[start];
            nums[start] = nums[end];
            nums[end] = temp;
            start++;
            end--;
        }
    }
    
    @Test
    public void testCase(){
        int []nums = {1,2,3,4,5};
        int k = 2;
        rotate(nums, k);
        System.out.println(Arrays.toString(nums));
    }
    @Test
    public void testCase2(){
        int []nums = {1,2};
        int k = 2;
        rotate(nums, k);
        System.out.println(Arrays.toString(nums));
    }
    @Test
    public void testCase3(){
        int []nums = {1,2};
        int k = 3;
        rotate(nums, k);
        System.out.println(Arrays.toString(nums));
    }
}
